<template>
  <div class="countDownContainer flex alignCenter">
    <view v-if="timeObj.d" class="shrink">{{timeObj.d}}天</view>
    <view v-if="timeObj.h" class="shrink">{{timeObj.h}}小时</view>
    <view v-if="timeObj.m" class="shrink">{{timeObj.m}}分钟</view>
    <view v-if="timeObj.s" class="shrink">{{timeObj.s}}秒</view>
  </div>
</template>

<script setup lang="ts">
let props = defineProps(["countDown"]);
let timer = null;
let countDown = ref(0);
let timeObj = ref({});

onMounted(() => {
  countDown.value = props.countDown;
  startCountDown();
});

function startCountDown() {
  let countDownTime = countDown.value;
  timer = setInterval(() => {
    countDownTime -= 1;
    if (countDownTime >= 0) {
      countDown.value = countDownTime;
      timeObj.value = timeLeft(countDownTime);
    } else {
      clearInterval(timer);
    }
  }, 1000); // 每1000毫秒更新一次
}

function timeLeft(diff) {
  // 如果差值小于等于0，则返回0天0时0分0秒
  if (diff <= 0) return { d: 0, h: 0, m: 0, s: 0 };

  // 计算天、时、分、秒
  const d = Math.floor(diff / (1000 * 60 * 60 * 24));
  const h = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  const m = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
  //const s = Math.floor((diff % (1000 * 60)) / 1000);
  const s = Math.floor(diff % 60);

  // 返回对象
  return { d, h, m, s };
}

onBeforeUnmount(() => {
  if (timer) clearInterval(timer);
});

onUnmounted(() => {
  if (timer) clearInterval(timer);
});

// watch(
//   () => props.countDown,
//   (newValue, oldValue) => {
//     if (newValue) {
//       countDown.value = newValue;
//       startCountDown();
//     }
//   },
//   { deep: true, immediate: true }
// );
</script>



<style lang="scss" scoped>
.countDownContainer {
}
</style>
